var crypto = require('crypto');
var url = require('url');

class api {
    //构造方法
    constructor({ curl }) {
        this.curl = curl
    }
    // 获取通讯录权限 
    // https://open-doc.dingtalk.com/docs/doc.htm?spm=a219a.7629140.0.0.5hnvyC&treeId=385&articleId=106091&docType=1#s0
    async scopes() {
        return await this.curl('/auth/scopes');
    }

    //获取js_ticket
    async getJsTicket() {
        return await this.curl('/get_jsapi_ticket')
    }

    //获取企业签名对象
    async getSingture(url) {
        var nonceStr = 'abcdefg';
        var timeStamp = new Date().getTime();
        var signedUrl = decodeURIComponent(url);
        let ret = await this.getJsTicket()
        let { ticket } = ret
        var signature = sign({
            nonceStr: nonceStr,
            timeStamp: timeStamp,
            url: signedUrl,
            ticket: ticket
        });
        return {
            signature: signature,
            nonceStr: nonceStr,
            timeStamp: timeStamp,
            corpId: 'ding3a8c9da236345ba135c2f4657eb6378f',
            jsApiList : [ 'runtime.info'] // 必填，需要使用的jsapi列表，注意：不要带dd。
        };
    }
}


function sign(params) {
    var origUrl = params.url;
    var origUrlObj = url.parse(origUrl);
    delete origUrlObj['hash'];
    var newUrl = url.format(origUrlObj);
    var plain = 'jsapi_ticket=' + params.ticket +
        '&noncestr=' + params.nonceStr +
        '&timestamp=' + params.timeStamp +
        '&url=' + newUrl;

    console.log(plain);
    var sha1 = crypto.createHash('sha1');
    sha1.update(plain, 'utf8');
    var signature = sha1.digest('hex');
    console.log('signature: ' + signature);
    return signature;
}

module.exports = api